//
//  EditIMViewController.m
//  cliqset
//
//  Created by David Hinson on 2/18/09.
//  Copyright 2009 Cliqset, Inc.. All rights reserved.
//

#import "EditIMViewController.h"
#import "ContactDetailViewController.h"
#import "cliqsetAppDelegate.h"
#import "Contact.h"

@implementation EditIMViewController

@synthesize ims;
@synthesize imField;
@synthesize imTypeField;
@synthesize parent;

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
	
	self.title = @"Edit IM";
	
	self.ims.backgroundColor = [UIColor clearColor];
	
	// Set save button
	UIBarButtonItem* saveButton = [[[UIBarButtonItem alloc] initWithTitle:@"Save" style:UIBarButtonItemStyleBordered target:self action:@selector(doSave:)] retain];
	self.navigationItem.rightBarButtonItem = saveButton;
	
	// Set cancel button
	UIBarButtonItem* cancelButton = [[[UIBarButtonItem alloc] initWithTitle:@"Cancel" style:UIBarButtonItemStyleBordered target:self action:@selector(doCancel:)] retain];
	self.navigationItem.leftBarButtonItem = cancelButton;
}

// Do cancel
-(void)doCancel:(id)id {
	cliqsetAppDelegate* myApp = (cliqsetAppDelegate*)[[UIApplication sharedApplication] delegate];
	NSLog(@"doCancel");
	
	[myApp slideIMOut];
}

// Do save
-(void)doSave:(id)id {
	cliqsetAppDelegate* myApp = (cliqsetAppDelegate*)[[UIApplication sharedApplication] delegate];
	
	if ([self.imField isEqualToString:@""]) {
		[myApp addTextToLog:@"IM Cannot Be Empty!" withCaption:@"Edit IM" ];
		return;
	}
	
	// Dereference our contact
	Contact *contact=nil; 
	if (self.parent.index>=0) {
	if (parent.isFavorite) {
		for (int x=0; x<[myApp.contacts count]; x++) {
			Contact *localContact = (Contact*)[myApp.contacts objectAtIndex:x]; 
			if ([localContact.contactIdentifier isEqualToString:[myApp.favorites objectAtIndex:parent.index]]) {
				contact = localContact;
				break;
			}
		}
	} 
	else {
		contact = (Contact *)[myApp.contacts objectAtIndex:parent.index];
	}
	} else {
		contact = self.parent.bufferContact;
	}
	
	NSLog(@"doSave");
	
	NSMutableString* strTag;
	if (parent.isPersonal) {
		strTag = (NSMutableString*)[@"" stringByAppendingFormat:@"%@", [[self.imTypeField capitalizedString] isEqualToString:@"Home"] ? @"Personal" : [self.imTypeField capitalizedString]];
		strTag = [strTag isEqualToString:@"Personal"] ? strTag : (NSMutableString*)[@"" stringByAppendingFormat:@"%@%@", @"Personal", strTag];
	}
	else {
		strTag = (NSMutableString*)[@"" stringByAppendingFormat:@"%@", [[self.imTypeField capitalizedString] isEqualToString:@"Office"] ? @"Work" : [self.imTypeField capitalizedString]];
		strTag = [strTag isEqualToString:@"Work"] ? strTag : (NSMutableString*)[@"" stringByAppendingFormat:@"%@%@", @"Work", strTag];
	}
	
	// Add through cliqset, if editing
	if (self.parent.index>=0) {
		[myApp.cliqset putIM:contact.contactIdentifier tag:strTag number:self.imField primary:NO];
		}
	
	// And add back to contact im screen names array
	IM * im = [[IM alloc] init];
	
	// Build im entry
	im.network = strTag;
	im.name    = self.imField;
	im.primary = NO;
	
	// Cycle through ims... we need to remove any existing with the same type
	for (int x=0; x<[contact.imScreenNames count]; x++) {
		IM * ti = (IM*)[contact.imScreenNames objectAtIndex:x];
		NSLog(@"%d  ti: [%@] - internal: [%@]", x, ti.network, strTag);
		if ([ti.network isEqualToString:strTag]) {
			[contact.imScreenNames removeObjectAtIndex:x];
			break;
		}
	}
	
	[contact.imScreenNames addObject:im];
	[im release];
	
	[myApp slideIMOut];
	[parent.contactDetailTable reloadData];	
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning]; // Releases the view if it doesn't have a superview
    // Release anything that's not essential, such as cached data
}

// Number of table sections
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
	return 2;
}

// Return rows in table
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
	
	switch (section) {
		case 0:
			return 1.0;
			break;
			
		case 1:
			return 1.0;
			break;
			
		default:
			return 0;
			break;
	}
}

// Set row height
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
	
	switch (indexPath.section) {
		case 0:
			return 40.0;
			break;
		case 1:
			return 40.0;
			break;
		default:
			break;
	}
	
	return 0.0;
}

// Indicate disclosure
- (UITableViewCellAccessoryType)tableView:(UITableView *)tableView accessoryTypeForRowWithIndexPath:(NSIndexPath *)indexPath
{
	if (indexPath.section == 1 && indexPath.row == 0) {
		return UITableViewCellAccessoryDisclosureIndicator;	
	} 
	else {
		return UITableViewCellAccessoryNone;
	}
}

// Draw cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
	
	UITableViewCell *cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:nil] autorelease];
    [cell backgroundView].opaque=YES;
    [cell backgroundView].clearsContextBeforeDrawing;
   	[cell setSelectionStyle:UITableViewCellSelectionStyleNone];
	
	UIFont* large_font      = [UIFont systemFontOfSize:18];
	UIColor* textColor      = [UIColor colorWithRed:62.0/255.0 green:62.0/255.0 blue:62.0/255.0 alpha:1.0];
	
	cell.hidesAccessoryWhenEditing = NO;
	
	UILabel * imLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 7, 290, 26)];
	UITextField * im   = [[UITextField alloc] initWithFrame:CGRectMake(20,7,290,46)];
	
	switch (indexPath.section) {
		case 0:
			
			im.textColor   = textColor;
			im.font        = large_font;
			im.placeholder = @"IM Name";
			
			im.keyboardType = UIKeyboardTypeEmailAddress;
			im.autocapitalizationType = UITextAutocapitalizationTypeNone;
			[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(imDidChange:) name:@"UITextFieldTextDidChangeNotification" object:im];
			im.text         = (!self.imField || [self.imField isEqualToString:@""]) ? @"" : self.imField;
			
			[im becomeFirstResponder];
			
			[cell addSubview:im];
			
			break;
		case 1:
			
			imLabel.textColor                 = textColor;
			imLabel.font                      = large_font;
			imLabel.adjustsFontSizeToFitWidth = NO;
			
			imLabel.text                      = (!self.imTypeField || [self.imTypeField isEqualToString:@""]) ? @"" : self.imTypeField;
			self.imTypeField                  = (NSMutableString*)imLabel.text;
			
			[cell addSubview:imLabel];
			break;
	}
	
	[imLabel release];
	[im release];

	//UIColor* myBGColor               = [UIColor colorWithRed:248.0/255.0 green:248.0/255.0 blue:248.0/255.0 alpha:1.0];
	//cell.backgroundView.backgroundColor = myBGColor;
	for ( UIView* view in cell.contentView.subviews ) 
	{
		view.backgroundColor = [ UIColor clearColor ];
	}
	
	return cell;
}	

// Row selected... 
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {	
	cliqsetAppDelegate* myApp = (cliqsetAppDelegate*)[[UIApplication sharedApplication] delegate];
	
	NSLog(@"didSelectRowAtIndexPath");
	
	UITableViewCell *hitCell = [tableView cellForRowAtIndexPath:indexPath];	
    [hitCell setSelected:NO animated:YES];
	
	if (indexPath.section == 1) {
		[myApp slideIMTypeIn:self];
	}
}

// Our im changed... save it
-(void)imDidChange:(id)textField {	
	self.imField = (NSMutableString*)[[textField object] text];
}

- (void)dealloc {
	[parent release];
	[imField release];
	[imTypeField release];
	[ims release];
    [super dealloc];
}


@end
